package zuoye8;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.ProgressMonitor;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class Zuoye7 {
	public static void main(String[] args) {
		WindowButton win = new WindowButton("猜数字");
	}
}

class WindowButton extends JFrame implements ActionListener {
	int number;
	JLabel hintLabel;
	JTextField inputGuess;
	JButton buttonGetNumber, buttonEnter;
	Timer timer;
	JOptionPane dlg;
	static ProgressMonitor pbar;
	static int count;

	WindowButton(String s) {
		super(s);
		addWindowListener(new WindowAdapter() { // �������ʵ�����Ӵ����¼�
			public void windowClosing(WindowEvent e) {
				dispose();
			}
		});
		setLayout(new FlowLayout());
		buttonGetNumber = new JButton("得到一个随机数");
		add(buttonGetNumber);
		hintLabel = new JLabel("输入你的猜测：", JLabel.CENTER);
		hintLabel.setBackground(Color.cyan);
		inputGuess = new JTextField("0", 10);
		///
		timer = new Timer(30000, this);
		dlg = new JOptionPane();
		pbar = new ProgressMonitor(null, "进度", "进度..", 0, 100);
		count=0;
		///
		add(hintLabel);
		add(inputGuess);
		buttonEnter = new JButton("确定");
		add(buttonEnter);
		buttonEnter.addActionListener(this);
		buttonGetNumber.addActionListener(this);
		setBounds(100, 100, 150, 150);
		setVisible(true);
		validate();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == buttonGetNumber) {
			//
			timer.start();
			count=0;
			//
			number = (int) (Math.random() * 100) + 1;
			hintLabel.setText("输入你的猜测：");
		}
		else if (e.getSource() == buttonEnter) {
			
			int guess = 0;
			//
			SwingUtilities.invokeLater(new Runnable(){
				public void run(){
					if(pbar.isCanceled()){
						pbar.close();
						System.exit(1);
					}
					pbar.setProgress(count);
					count += 1;
					pbar.setNote("你猜了：" + count + " 次");
					
				}
			});
			//
			try {
				guess = Integer.parseInt(inputGuess.getText());
				if (guess == number) {
					hintLabel.setText("对了");
					//
					if (timer.isRunning()) {
						dlg.showMessageDialog(null, "你赢了", "提示", JOptionPane.DEFAULT_OPTION);
					}
					//
				}
				else if (guess > number) {
					hintLabel.setText("大了");
					inputGuess.setText(null);
				}
				else if (guess < number) {
					hintLabel.setText("小了");
					inputGuess.setText(null);
				}
			}
			catch (NumberFormatException event) {
				hintLabel.setText("输入数字：");
			}
		}
		//
		else if (e.getSource() == timer) {
			dlg.showMessageDialog(null, "你输了", "提示", JOptionPane.CLOSED_OPTION);

			timer.stop();
			
		}
		//
	}
}